package io.github.mymonstercat.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSON;
import io.github.mymonstercat.entity.FileData;
import io.github.mymonstercat.service.TicketVisitsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@Service
public class TicketVisitsServiceImpl implements TicketVisitsService {

    @Resource
    private Environment environment;

    @Override
    public void saveVisits(String message, String type) {
        String path = getPath(type);
        saveMessageToFile(path, createFileData(message, IdUtil.simpleUUID()));
    }

    @Override
    public void saveVisits(String message, String type, String fileId) {
        String path = getPath(type);
        saveMessageToFile(path, createFileData(message, fileId));
    }

    private String createFileData(String message, String fileId) {
        FileData fileData = new FileData();
        fileData.setId(fileId);
        fileData.setTime(getNowTime());
        fileData.setDetail(message);
        return JSON.toJSONString(fileData);
    }

    private String getPath(String type) {
        String osName = System.getProperty("os.name");
        if (osName.startsWith("Windows")) {
            return "visits".equals(type) ? environment.getProperty("file.visits.windows") : environment.getProperty("file.log.windows");
        } else {
            return "visits".equals(type) ? environment.getProperty("file.visits.linux") : environment.getProperty("file.log.linux");
        }
    }


    /**
     * 将内容保存到文件中
     *
     * @param path    文件路径
     * @param jsonStr 保存内容
     */
    private void saveMessageToFile(String path, String jsonStr) {
        File logFile = new File(path + "/log.json"); // 指定日志文件路径

        // 确保日志文件存在，如果不存在则尝试创建
        if (!logFile.exists()) {
            File directory = logFile.getParentFile();
            if (!directory.exists()) {
                boolean mkdirs = directory.mkdirs();
                log.info("文件创建标识: {}", mkdirs);
            }
            try {
                boolean newFile = logFile.createNewFile();
                log.info("文件创建标识: {}", newFile);
            } catch (IOException e) {
                // 处理异常，例如记录到错误日志
                e.printStackTrace();
            }
        }

        // 确保有权限写入日志文件
        if (logFile.canWrite()) {
            // 开启追加模式
            try (FileWriter fw = new FileWriter(logFile, true);
                 BufferedWriter bw = new BufferedWriter(fw)) {
                bw.write(jsonStr + "," + "\n");
            } catch (IOException e) {
                // 处理异常，例如记录到错误日志
                e.printStackTrace();
            }
        } else {
            // 处理没有写权限的情况，例如记录到错误日志
            log.error("No write permission for log file.");
        }
    }

    /**
     * 获取现在的时间
     *
     * @return String
     */
    private String getNowTime() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return now.format(formatter);
    }
}
